<template>
  <div class="dialog" v-show="visible" @click.self="close">
    <div class="dialog-wrap">
      <div class="dialog-header">
        <p class="dialog-header-title"><slot name="header" /></p>
        <button class="dialog-header-btn" @click="close">X</button>
      </div>
      <div class="dialog-body">
        <slot />
      </div>
      <div class="dialog-footer">
        <slot name="footer" />
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "Dialog",
  props: {
    visible: {
      type: Boolean,
      required: true,
    },
  },
  methods: {
    close() {
      this.$emit("update:visible", false);
    },
  },
  watch: {
    visible: {
      handler(visible) {
        if (visible) {
          // 禁用滚动条
          document.documentElement.style["overflow-y"] = "hidden";
        } else {
          // 启用滚动条
          document.documentElement.style["overflow-y"] = "auto";
        }
      },
      immediate: true,
    },
  },
};
</script>

<style lang="less" scoped>
.dialog {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: rgba(0, 0, 0, 0.3);
}
.dialog-wrap {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  width: 400px;
  padding: 10px 20px;
  box-sizing: border-box;
  border-radius: 3px;
  background: #fff;
}
.dialog-header {
  display: flex;
  justify-content: space-between;
}
.dialog-header-title {
  font-size: 20px;
}
.dialog-header-btn {
  border: none;
  outline: none;
  background-color: #fff;
  cursor: pointer;
  &:hover {
    color: yellowgreen;
  }
}
.dialog-body {
  padding: 20px 0;
  font-size: 14px;
}
</style>
